package com.gtc.zsk.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gtc.zsk.annotation.AuthCheck;
import com.gtc.zsk.common.BaseResponse;
import com.gtc.zsk.common.DeleteRequest;
import com.gtc.zsk.common.ErrorCode;
import com.gtc.zsk.common.ResultUtils;
import com.gtc.zsk.constant.UserConstant;
import com.gtc.zsk.exception.BusinessException;
import com.gtc.zsk.exception.ThrowUtils;
import com.gtc.zsk.model.dto.questionApply.QuestionApplyAddRequest;
import com.gtc.zsk.model.dto.questionApply.QuestionApplyEditRequest;
import com.gtc.zsk.model.dto.questionApply.QuestionApplyQueryRequest;
import com.gtc.zsk.model.dto.questionApply.QuestionApplyUpdateRequest;
import com.gtc.zsk.model.entity.QuestionApply;
import com.gtc.zsk.model.entity.User;
import com.gtc.zsk.model.vo.QuestionApplyVO;
import com.gtc.zsk.service.QuestionApplyService;
import com.gtc.zsk.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 題库题目审核接口
 *
 * @author <a href="https://github.com/ligtc">程序员鱼皮</a>
 * @from <a href="https://www.code-nav.cn">编程导航学习圈</a>
 */
@RestController
@RequestMapping("/questionApply")
@Slf4j
public class QuestionApplyController {

    @Resource
    private QuestionApplyService questionApplyService;

    @Resource
    private UserService userService;

    // region 增删改查

    /**
     * 创建題库题目审核
     *
     * @param questionApplyAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addQuestionApply(@RequestBody QuestionApplyAddRequest questionApplyAddRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(questionApplyAddRequest == null, ErrorCode.PARAMS_ERROR);
        // todo 在此处将实体类和 DTO 进行转换
        QuestionApply questionApply = new QuestionApply();
        BeanUtils.copyProperties(questionApplyAddRequest, questionApply);
        // 数据校验
        questionApplyService.validQuestionApply(questionApply, true);
        // todo 填充默认值
        User loginUser = userService.getLoginUser(request);
        questionApply.setUserId(loginUser.getId());
        // 写入数据库
        boolean result = questionApplyService.save(questionApply);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        // 返回新写入的数据 id
        long newQuestionApplyId = questionApply.getId();
        return ResultUtils.success(newQuestionApplyId);
    }

    /**
     * 删除題库题目审核
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteQuestionApply(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        QuestionApply oldQuestionApply = questionApplyService.getById(id);
        ThrowUtils.throwIf(oldQuestionApply == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!oldQuestionApply.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 操作数据库
        boolean result = questionApplyService.removeById(id);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 更新題库题目审核（仅管理员可用）
     *
     * @param questionApplyUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateQuestionApply(@RequestBody QuestionApplyUpdateRequest questionApplyUpdateRequest) {
        if (questionApplyUpdateRequest == null || questionApplyUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // todo 在此处将实体类和 DTO 进行转换
        QuestionApply questionApply = new QuestionApply();
        BeanUtils.copyProperties(questionApplyUpdateRequest, questionApply);
        // 数据校验
        questionApplyService.validQuestionApply(questionApply, false);
        // 判断是否存在
        long id = questionApplyUpdateRequest.getId();
        QuestionApply oldQuestionApply = questionApplyService.getById(id);
        ThrowUtils.throwIf(oldQuestionApply == null, ErrorCode.NOT_FOUND_ERROR);
        // 操作数据库
        boolean result = questionApplyService.updateById(questionApply);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 根据 id 获取題库题目审核（封装类）
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<QuestionApplyVO> getQuestionApplyVOById(long id, HttpServletRequest request) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        QuestionApply questionApply = questionApplyService.getById(id);
        ThrowUtils.throwIf(questionApply == null, ErrorCode.NOT_FOUND_ERROR);
        // 获取封装类
        return ResultUtils.success(questionApplyService.getQuestionApplyVO(questionApply, request));
    }

    /**
     * 分页获取題库题目审核列表（仅管理员可用）
     *
     * @param questionApplyQueryRequest
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<QuestionApply>> listQuestionApplyByPage(@RequestBody QuestionApplyQueryRequest questionApplyQueryRequest) {
        long current = questionApplyQueryRequest.getCurrent();
        long size = questionApplyQueryRequest.getPageSize();
        // 查询数据库
        Page<QuestionApply> questionApplyPage = questionApplyService.page(new Page<>(current, size),
                questionApplyService.getQueryWrapper(questionApplyQueryRequest));
        return ResultUtils.success(questionApplyPage);
    }

    /**
     * 分页获取題库题目审核列表（封装类）
     *
     * @param questionApplyQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<QuestionApplyVO>> listQuestionApplyVOByPage(@RequestBody QuestionApplyQueryRequest questionApplyQueryRequest,
                                                               HttpServletRequest request) {
        long current = questionApplyQueryRequest.getCurrent();
        long size = questionApplyQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<QuestionApply> questionApplyPage = questionApplyService.page(new Page<>(current, size),
                questionApplyService.getQueryWrapper(questionApplyQueryRequest));
        // 获取封装类
        return ResultUtils.success(questionApplyService.getQuestionApplyVOPage(questionApplyPage, request));
    }

    /**
     * 分页获取当前登录用户创建的題库题目审核列表
     *
     * @param questionApplyQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/my/list/page/vo")
    public BaseResponse<Page<QuestionApplyVO>> listMyQuestionApplyVOByPage(@RequestBody QuestionApplyQueryRequest questionApplyQueryRequest,
                                                                 HttpServletRequest request) {
        ThrowUtils.throwIf(questionApplyQueryRequest == null, ErrorCode.PARAMS_ERROR);
        // 补充查询条件，只查询当前登录用户的数据
        User loginUser = userService.getLoginUser(request);
        questionApplyQueryRequest.setUserId(loginUser.getId());
        long current = questionApplyQueryRequest.getCurrent();
        long size = questionApplyQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<QuestionApply> questionApplyPage = questionApplyService.page(new Page<>(current, size),
                questionApplyService.getQueryWrapper(questionApplyQueryRequest));
        // 获取封装类
        return ResultUtils.success(questionApplyService.getQuestionApplyVOPage(questionApplyPage, request));
    }

    /**
     * 编辑題库题目审核（给用户使用）
     *
     * @param questionApplyEditRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editQuestionApply(@RequestBody QuestionApplyEditRequest questionApplyEditRequest, HttpServletRequest request) {
        if (questionApplyEditRequest == null || questionApplyEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // todo 在此处将实体类和 DTO 进行转换
        QuestionApply questionApply = new QuestionApply();
        BeanUtils.copyProperties(questionApplyEditRequest, questionApply);
        // 数据校验
        questionApplyService.validQuestionApply(questionApply, false);
        User loginUser = userService.getLoginUser(request);
        // 判断是否存在
        long id = questionApplyEditRequest.getId();
        QuestionApply oldQuestionApply = questionApplyService.getById(id);
        ThrowUtils.throwIf(oldQuestionApply == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可编辑
        if (!oldQuestionApply.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 操作数据库
        boolean result = questionApplyService.updateById(questionApply);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    // endregion
}
